use crate::{
    models::{date_range::DateRange, personnel::ResPersonnel},
    reply::Reply,
    state::State,
};
use entity::{
    department, personnel, position,
    prelude::{Department, Personnel, Position, Resignation},
    resignation,
};
use poem::{
    handler,
    web::{Data, Query},
};
use sea_orm::{prelude::Date, ColumnTrait, EntityTrait, QueryFilter, QueryOrder, QuerySelect};

#[handler]
pub async fn batch(
    Data(State { db, .. }): Data<&State>,
    Query(DateRange { start, end }): Query<DateRange<Option<Date>, Option<Date>>>,
) -> Reply<Vec<ResPersonnel>> {
    let mut reader = Personnel::find()
        .left_join(Resignation)
        .inner_join(Department)
        .inner_join(Position)
        .filter(personnel::Column::IsEmployed.eq(false))
        .order_by_asc(resignation::Column::ResignDate)
        .select_only()
        .column(personnel::Column::Id)
        .column(personnel::Column::Name)
        .column_as(department::Column::Name, "department")
        .column_as(position::Column::Name, "position")
        .column(resignation::Column::Kind)
        .column(resignation::Column::ResignDate);

    if let Some(start) = start {
        reader = reader.filter(resignation::Column::ResignDate.gte(start));
    }

    if let Some(end) = end {
        reader = reader.filter(resignation::Column::ResignDate.lte(end));
    }

    let resignations = reader.into_model::<ResPersonnel>().all(db).await.unwrap();

    Reply::new().data(resignations)
}
